import React, { useRef } from 'react';
import { AttachmentIcon } from './Icons';
import { File as AppFile } from '../types/chat';

interface FileSelectProps {
  onSelected: (file: AppFile) => void;
  userId?: string | number;
  accept?: string;
  multiple?: boolean;
}

const FileSelect: React.FC<FileSelectProps> = ({
  onSelected,
  userId,
  accept = '*',
  multiple = false
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  
  const handleClick = () => {
    if (fileInputRef.current) {
      fileInputRef.current.click();
    }
  };
  
  const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files.length > 0) {
      const file = e.target.files[0]; // 只取第一个文件
      handleFile(file);
      
      // 重置文件输入，以便可以再次选择相同的文件
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleFile = (file: File) => {
    // 创建一个包含用户ID的FormData对象
    const formData = new FormData();
    formData.append('file', file);
    if (userId) {
      formData.append('userId', userId.toString());
    }
    
    // 这里可以添加上传文件的逻辑
    // 假设上传成功后，将文件信息传递给onSelected回调
    const fileInfo: AppFile = {
      name: file.name,
      size: file.size,
      type: file.type,
      url: URL.createObjectURL(file),
      // 其他需要的文件信息
    };
    
    onSelected(fileInfo);
  };
  
  return (
    <button 
      className="tool-item-btn"
      onClick={handleClick}
      title="上传文件"
    >
      <AttachmentIcon className="icon" />
      <input 
        type="file"
        ref={fileInputRef}
        style={{ display: 'none' }}
        accept={accept}
        multiple={multiple}
        onChange={handleFileChange}
      />
    </button>
  );
};

export default FileSelect; 